/** 
*人员选择弹窗
*/
<template>
	<vp-dialog ref="dialogRef" :span=2>
		<template #title>{{$t('user.selectUser')}}
			<vp-label zh="选择用户" en="Select User" align="left"/>
		</template>
		<vp-card shadow="hover" class="mb5">
			<el-form label-suffix=":"  ref="searchFormRef" :model="searchForm" @submit.prevent
				@keyup.enter="handleSearch" label-width="120px">
				<vp-search-row :show-more="showMore">
					<vp-search-col>
						<el-form-item prop="keyword">
							<template #label><vp-label-keyword/></template>
							<el-input v-model="searchForm.keyword" v-trim placeholder=""></el-input>
						</el-form-item>
					</vp-search-col>
					<vp-search-col>
						<el-form-item prop="bmdm">
							<template #label><vp-label zh="部门" en="Department"/></template>
							<vp-department-select-tree :selectedId="searchForm.bmdm" :selectedText="searchForm.bmmc" @treeSelected="handleDepartmentSelected" class="w100"/>
						</el-form-item>
					</vp-search-col>
					<vp-search-col btn-col>
						<vp-btn-search :loading="loading" @click="loadDataList"/>
						<vp-btn-reset @click="handleSearchReset"/>
						<vp-btn-more @change="showMore = $event"/>
					</vp-search-col>
				</vp-search-row>
			</el-form>
		</vp-card>
		<vp-card shadow="hover" v-loading="loading">
			<vp-table ref="tableRef" :data="tableData" @sort-change="handleSortChange"
				:height="`calc(100vh - 450px - ${showMore?'47px':'0px'}`" stripe border  class="w100"
				row-key="id" highlight-current-row @current-change="handleCurrentChange"
				@row-click="handleRowClick"
				@selection-change="handleSelectionChange">
				<el-table-column v-if="options.multi" type="selection">
				</el-table-column>
				<el-table-column  type="index" align="center" label="#">
				</el-table-column>
				<el-table-column :label="$t('user.username')" sortable="custom" prop="username"
					show-overflow-tooltip>
					<template #header><vp-label zh="用户名" en="Account"/></template>
					<template #default="scope">
						<span v-html="markTextColor(searchForm.keyword, scope.row.username)" />
					</template>
				</el-table-column>
				<el-table-column :label="$t('user.realname')" prop="realname" sortable="custom"
					show-overflow-tooltip>
					<template #header><vp-label zh="姓名" en="Name"/></template>
					<template #default="scope">
						<span v-html="markTextColor(searchForm.keyword, scope.row.realname)" />
					</template>
				</el-table-column>
				<el-table-column :label="$t('department.dprtname')" prop="department.dprtname"
					show-overflow-tooltip>
					<template #header><vp-label zh="部门" en="Department"/></template>
				</el-table-column>
				<!-- <el-table-column :label="$t('item.base')" prop="area.qy" show-overflow-tooltip>
				</el-table-column> -->
				<el-table-column :label="$t('user.zw')" prop="zw" show-overflow-tooltip>
					<template #header><vp-label zh="职务" en="Position"/></template>
				</el-table-column>
			</vp-table>
			<el-pagination background class="mt5" layout="prev, pager, next, total, ->, slot" :total="page.total"
				v-model:currentPage="page.pageNum" v-model:pageSize="page.pageSize" :hide-on-single-page="false">
				<el-popover placement="top-end" :width="400" trigger="click" v-if="options.multi">
					<template #reference>
						<el-badge :value="currentTableSelected.length" type="primary">
							<el-button >{{$t('item.selected')}}</el-button>
						</el-badge>
					</template>
					<el-table :data="currentTableSelected"  border stripe max-height="500" row-key="id">
						<el-table-column :label="$t('user.username')" prop="username"><template #header><vp-label zh="用户名" en="Account"/></template></el-table-column>
						<el-table-column :label="$t('user.realname')" prop="realname"><template #header><vp-label zh="姓名" en="Name"/></template></el-table-column>
						<el-table-column :label="$t('item.operation')" width="55">
							<template #header>
								<vp-label-operations/>
							</template>
							<template #default="{row}">
								<el-button type="text"  @click="handleSelectedDelete(row)">
									{{$t('btn.delete')}}</el-button>
							</template>
						</el-table-column>
					</el-table>
				</el-popover>
			</el-pagination>
		</vp-card>
		<template #footer>
			<vp-btn type="danger" @click="handleClear"><vp-label zh="清空" en="Empty"/></vp-btn>
			<vp-btn-confirm @click="handleConfirm"/>
		</template>
	</vp-dialog>
</template>

<script lang="ts">
	import {
		ref,
		toRefs,
		reactive,
		watch,
		computed
	} from 'vue';
	import request from '/@/utils/request';
	import {
		markTextColor
	} from '/@/utils/toolsValidate';
import { storeToRefs } from 'pinia';
import { useUserInfo } from '/@/stores/userInfo';
	export default {
		name: 'userSelectDialog',
		components: {
		},
		props: {
			containCurrentLoginUser: {
				type: Boolean,
				default: true,
			},
		},
		emits: ['userSelected'],
		setup(props, context) {
			const state = reactive({
				searchForm: {
					keyword: "",
					bmdm: "",
					bmmc: "",
					jddm: "",
					state: 1,
				},
				page: {
					total: 0, // 总条数
					pageNum: 1, // 当前页
					pageSize: 10, // 分页大小
					sortColumn: "",
					sortOrder: ""
				},
				showMore: false,
				loading: false,
				tableData: [],
				currentTableSelected: [],
				selected: [],
				options: {
					type: '', //标识
					multi: false, //默认单选
				}
			});
			const initState = () => {
				state.searchForm = {
					keyword: "",
					bmdm: "",
					bmmc: "",
					jddm: "",
					state: 1,
				}
				state.page = {
						total: 0, // 总条数
						pageNum: 1, // 当前页
						pageSize: 10, // 分页大小
						sortColumn: "",
						sortOrder: ""
					},
					state.showMore = false,
					state.loading = false,
					state.tableData = [],
					state.currentTableSelected = [],
					state.selected = [],
					state.options = {
						type: '', //标识
						multi: false, //默认单选
					}
			}
			const dialogRef = ref();
			const tableRef = ref();
			const stores = useUserInfo();
			const { userInfos } = storeToRefs(stores);

			const loadDataList = () => {
				state.loading = true
				if (state.options.multi) {
					if (state.currentTableSelected.length > 0) {
						state.currentTableSelected.forEach((val) => {
							state.selected.push(formatObject(val));
						});
						tableRef.value.clearSelection();
					}
				}
				request.get('/system/user/list', {
					params: {
						...state.searchForm,
						...state.page,
					}
				}).then(res => {
					state.tableData = res?.data?.list || []
					state.page.total = res?.data?.total || 0
					state.page.pageNum = res?.data?.pageNum || 1
					if (!props.containCurrentLoginUser && (userInfos as any).user.id) {
						state.tableData.forEach((user,index) => {
							if ((userInfos as any).user.id  === user.id) {
								state.tableData.splice(index, 1);
							}
						})
					}
					
					if (state.options.multi && state.selected.length > 0) {
						state.selected = state.selected.filter((val) => {
							let flag = true;
							state.tableData.forEach((val1) => {
								if (val1.id === val.id) {
									tableRef.value.toggleRowSelection(val1, true);
									flag = false;
									return;
								}
							})
							return flag;
						});
					}
				}).finally(() => {
					state.loading = false
				})
			}

			const searchFormRef = ref();

			const handleSearch = () => {
				if (state.page.pageNum == 1) {
					loadDataList()
				} else {
					state.page.pageNum = 1
				}
			}
			const handleSearchReset = () => {
				searchFormRef.value.resetFields();
				state.searchForm.bmmc = "";
			}
			const handleSortChange = (column: any) => {
				state.page.sortColumn = column.prop;
				state.page.sortOrder = column.order == 'descending' ? 'desc' : 'asc'
				loadDataList()
			}
			watch(() => state.page.pageNum, () => {
				loadDataList()
			})

			const handleDepartmentSelected = (data: any) => {
				state.searchForm.bmdm = data.id;
				state.searchForm.bmmc = data.label;
			}
			const handleBaseSelected = (data: any) => {
				state.searchForm.jddm = data.id;
			}

			const handleOpen = (options: any) => {
				initState();
				state.options = {
					...state.options,
					...options,
				}
				if (options.selected && options.selected.length > 0) {
					options.selected.forEach((val: any) => {
						state.selected.push(formatObject(val));
					});
				}
				dialogRef.value.handleOpen();
				loadDataList();
			}

			const handleConfirm = () => {
				let selected = [];
				if (state.options.multi && state.currentTableSelected.length > 0) {
					selected = state.currentTableSelected.map((val) => {
						return formatObject(val);
					})
					selected = state.selected.concat(selected);
				} else {
					selected = state.selected;
				}
				context.emit('userSelected', {
					type: state.options.type,
					data: selected,
				})
				dialogRef.value.handleClose();
			}

			/**
			 * 清空所有选择项并返回
			 */
			const handleClear = ()=>{
				context.emit('userSelected', {
					type: state.options.type,
					data: [],
				})
				dialogRef.value.handleClose();
			}

			//将用户对象转为已选择对象
			const formatObject = (row: any) => {
				if (row == null) {
					return null;
				}
				let bmdm = "";
				let bmmc = "";
				if (row.department) {
					bmdm = row.department.id;
					bmmc = row.department.dprtname;
				}
				let qyid = "";
				let qymc = "";
				if (row.area) {
					qyid = row.area.id;
					qymc = row.area.qy;
				}
				return {
					id: row.id,
					username: row.username,
					realname: row.realname,
					sex: row.sex,
					bmdm: bmdm,
					bmmc: bmmc,
					qyid: qyid,
					qymc: qymc,
				};
			}

			const handleCurrentChange = (row: any) => {
				if (state.options.multi) {
					return;
				}
				state.selected = [];
				state.selected.push(formatObject(row))
			}

			const handleSelectionChange = (selected: any) => {
				if (!state.options.multi) {
					return;
				}
				state.currentTableSelected = selected;
			}

			const handleSelectedDelete = (row: any) => {
				state.selected = state.selected.filter((val) => {
					return val.id !== row.id
				})
				state.currentTableSelected.forEach(val => {
					if (val.id === row.id) {
						tableRef.value.toggleRowSelection(val, false);
					}
				})
			}

			const allSelected = computed(() => {
				let selected = [];
				if (state.options.multi && state.currentTableSelected.length > 0) {
					selected = state.currentTableSelected.map((val) => {
						return formatObject(val);
					})
					selected = state.selected.concat(selected);
				} else {
					selected = state.selected;
				}
				return selected;
			})

			const handleRowClick = (row: any) => {
				if (state.options.multi) {
					tableRef.value.toggleRowSelection(row);
				}
			}

			return {
				...toRefs(state),
				dialogRef,
				searchFormRef,
				handleSearch,
				handleSearchReset,
				handleSortChange,
				loadDataList,
				markTextColor,
				handleDepartmentSelected,
				handleBaseSelected,
				handleOpen,
				handleConfirm,
				handleCurrentChange,
				handleSelectionChange,
				tableRef,
				handleSelectedDelete,
				allSelected,
				handleRowClick,
				handleClear,
			}
		},

	}
</script>
